import type { IRentChangeStore, IRentMachineOrderInfoList } from "@/types/rentMachineManage/rentMachineOrderInfo";
import type { ISearchOtherStore, IStoreInfoList } from "@/types/storeManager/store";
import { putChangeStoreInfo } from "@/utils/api/admin/order/rentOrder";

/* 修改选择店铺 */
function useChangeStore(toggleState: (status: boolean) => void, tableList: Ref<IRentMachineOrderInfoList[]>) {
  const changeStoreVisible = ref(false);
  const changeStoreForm = ref<IRentChangeStore>({
    id: 0,
    store_id: ""
  });
  const otherSearchCondition = ref<ISearchOtherStore>({
    support_all_mobile: [],
    support_by_store: ""
  });

  /* 选择店铺信息 模态框 */
  function handleChangeStore(row: IRentMachineOrderInfoList) {
    changeStoreVisible.value = true;
    changeStoreForm.value.id = row.id;
    otherSearchCondition.value.support_by_store = 1;
    if (row.is_old_mobile === 0) {
      otherSearchCondition.value.support_all_mobile = ["ONLY_SUPPORT_NEW", "SUPPORT_ALL"];
    } else {
      otherSearchCondition.value.support_all_mobile = ["ONLY_SUPPORT_OLD", "SUPPORT_ALL"];
    }
  }

  /* 选择选中的店铺数据 */
  function handleSelected1Data(list: IStoreInfoList[]) {
    changeStoreVisible.value = false;
    changeStoreForm.value.store_id = list[0].id;

    handlePutChangeStoreInfo(list[0]);
  }

  /* 变更到店自提店铺 */
  function handlePutChangeStoreInfo(data: IStoreInfoList) {
    toggleState(true);
    putChangeStoreInfo(changeStoreForm.value)
      .then(res => {
        ElMessage.success(res.msg);
        /* 修改订单状态 */
        const item = tableList.value.find(order => order.id === changeStoreForm.value.id);
        if (!item) return;
        item.bindStore.store_id = data.store_id;
        item.bindStore.store_phone = data.store_phone;
        item.bindStore.store_name = data.store_name;
      })
      .catch(() => {})
      .finally(() => {
        toggleState(false);
      });
  }

  return {
    changeStoreVisible,
    otherSearchCondition,
    handleChangeStore,
    handleSelected1Data
  };
}

export default useChangeStore;
